//package com.match.competition_security.filter;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.match.commonutils.Const;
//import com.match.competition_security.exception.CaptchaException;
//
//import com.match.entity.loginEntity.LoginUser;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import javax.servlet.FilterChain;
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
//public class CaptchaFilter extends OncePerRequestFilter {
//    @Autowired
//    RedisUtils redisUtils;
//
//    private TokenLoginFilter tokenLoginFilter;
//    public CaptchaFilter(TokenLoginFilter tokenLoginFilter){
//        this.tokenLoginFilter=tokenLoginFilter;
//    }
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        String url = httpServletRequest.getRequestURI();
//
//        if ("/admin/competition_role/login".equals(url) && httpServletRequest.getMethod().equals("POST")) {
//
//            try{
//                // 校验验证码
//                validate(httpServletRequest);
//            } catch (CaptchaException e) {
//                // 交给认证失败处理器
//                tokenLoginFilter.unsuccessfulAuthentication(httpServletRequest, httpServletResponse, e);
//            }
//        }
//
//        filterChain.doFilter(httpServletRequest, httpServletResponse);
//    }
//
//
//    // 校验验证码逻辑
//    private void validate(HttpServletRequest httpServletRequest) throws IOException {
////        String code = httpServletRequest.getParameter("code");
////        String key = httpServletRequest.getParameter("token");
//
//        LoginUser user = new ObjectMapper().readValue(httpServletRequest.getInputStream(), LoginUser.class);
//        String code = user.getCode();
//        String key = user.getToken();
//        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(key)) {
//            throw new CaptchaException("验证码不能为空");
//        }
//
//        if (!code.equals(redisUtils.hget(Const.CAPTCHA_KEY, key))) {
//            throw new CaptchaException("验证码错误");
//        }
//
//        // 一次性使用
//        redisUtils.hdel(Const.CAPTCHA_KEY, key);
//    }
//    }
